#include "mysqlconnet.h"


//MysqlConnet::MysqlConnet(QWidget *parent) : QWidget(parent)
//{
//}

MysqlConnet::MysqlConnet()
{
   if(!mysql_commit(m_MysqlConn))
   {
    cout<<"初始化m_MySql失败"<<endl;
   };
   //设置字符串编码utf8
   mysql_set_character_set(m_MysqlConn,"utf8");
}

MysqlConnet::~MysqlConnet()
{
    //判断连接是否为空，如果不为空就关闭
    if(m_MysqlConn!=nullptr)
    {
        mysql_close(m_MysqlConn);
    }
}

void MysqlConnet::Init()
{

}

MYSQL* MysqlConnet::Connet(string* username, string* passwd, string* Ip, unsigned int port, string* db)
{
     m_MysqlConn = mysql_real_connect(m_MysqlConn,Ip->c_str(),username->c_str(),passwd->c_str(),db->c_str(),port,NULL,0);
    if(!m_MysqlConn)
    {
        return m_MysqlConn;
    }
    else
    {
        cout<<"m_MysqlConn数据库链接错误"<<endl;
    }
}

bool MysqlConnet::Update(string sql)
{
    if(mysql_query(m_MysqlConn,sql.c_str()))
    {
        return false;
    }
    return true;
}

bool MysqlConnet::Query(string sql)
{
    if(mysql_query(m_MysqlConn,sql.c_str()))
    {
        return false;
    }
    m_Result = mysql_store_result(m_MysqlConn);
    return true;
}

bool MysqlConnet::Next()
{
    if(m_Result!=nullptr)
    {
        m_Row = mysql_fetch_row(m_Result);
    }
}

string MysqlConnet::Value(int index)
{
    int rowCount = mysql_num_fields(m_Result);
    if(index >= rowCount || index <0)
    {
        return string();
    }
    char* val = m_Row[index];
    unsigned long length = mysql_fetch_lengths(m_Result)[index];
    return string(val,length);
}

bool MysqlConnet::Transaction()
{
    return mysql_autocommit(m_MysqlConn,false);
}

bool MysqlConnet::Commit()
{
    return mysql_commit(m_MysqlConn);
}

bool MysqlConnet::RollBack()
{
    return mysql_rollback(m_MysqlConn);
}
